home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-9.10-netbook-remix-PL.iso / casper / filesystem.squashfs / usr / share / pyshared / nevow / livepage.pyc (.txt) < prev    next >
Python Compiled Bytecode  |  2009-03-23  |  41KB  |  931 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. '''Provides a bidirectional channel for sending out-of-band
  5. events between client and server without refreshing the whole
  6. page.
  7. '''
  8. import itertools
  9. import types
  10. import warnings
  11. from zope.interface import implements, Interface
  12. from twisted.internet import defer, error
  13. from twisted.internet.task import LoopingCall
  14. from twisted.python import log
  15. from nevow import tags, inevow, context, static, flat, rend, url, util, stan
  16. DEBUG = False
  17. _jslog = None
  18.  
  19. def _openjslog():
  20.     global _jslog
  21.     if _jslog is None:
  22.         _jslog = file('js.log', 'w')
  23.         _jslog.write('**********\n')
  24.         _jslog.flush()
  25.     
  26.     return _jslog
  27.  
  28.  
  29. def jslog(*x):
  30.     if DEBUG:
  31.         mylog = _openjslog()
  32.         for y in x:
  33.             mylog.write(str(y))
  34.         
  35.         mylog.flush()
  36.     
  37.  
  38.  
  39. class JavascriptContext(context.WovenContext):
  40.     
  41.     def __init__(self, parent = None, tag = None, isAttrib = None, inJSSingleQuoteString = None, remembrances = None):
  42.         super(JavascriptContext, self).__init__(parent, tag, inJS = True, isAttrib = isAttrib, inJSSingleQuoteString = inJSSingleQuoteString, remembrances = None)
  43.  
  44.  
  45.  
  46. class TimeoutException(Exception):
  47.     pass
  48.  
  49.  
  50. class ClientSideException(Exception):
  51.     pass
  52.  
  53.  
  54. class SingleQuote(object):
  55.     
  56.     def __init__(self, children):
  57.         self.children = children
  58.  
  59.     
  60.     def __repr__(self):
  61.         return '%s(%s)' % (type(self).__name__, self.children)
  62.  
  63.  
  64.  
  65. def flattenSingleQuote(singleQuote, ctx):
  66.     new = JavascriptContext(ctx, tags.invisible[singleQuote], inJSSingleQuoteString = True)
  67.     return flat.serialize(singleQuote.children, new)
  68.  
  69. flat.registerFlattener(flattenSingleQuote, SingleQuote)
  70.  
  71. class _js(object):
  72.     '''Stan for Javascript. There is a convenience instance of this
  73.     class named "js" in the livepage module which you should use
  74.     instead of the _js class directly.
  75.  
  76.     Marker indicating literal Javascript should be rendered.
  77.     No escaping will be performed.
  78.  
  79.     When inside a JavascriptContext, Nevow will automatically put
  80.     apostrophe quote marks around any Python strings it renders.
  81.     This makes turning a Python string into a JavaScript string very
  82.     easy. However, there are often situations where you wish to
  83.     generate some literal Javascript code and do not wish quote
  84.     marks to be placed around it. In this situation, the js object
  85.     should be used.
  86.  
  87.     The simplest usage is to simply pass a python string to js.
  88.     When the js object is rendered, the python string will be
  89.     rendered as if it were literal javascript. For example:
  90.  
  91.         client.send(js("alert(\'hello\')"))
  92.  
  93.     However, to make the generation of Javascript more
  94.     convenient, the js object also provides safe implementations
  95.     of __getattr__, __call__, and __getitem__. See the following
  96.     examples to get an idea of how to use it. The Python code
  97.     is to the left of the -> and the Javascript which results is
  98.     to the right.
  99.  
  100.         js("alert(\'any javascript you like\')") -> alert(\'any javascript you like\')
  101.  
  102.         js.window.title -> window.title
  103.  
  104.         js.document.getElementById(\'foo\') -> document.getElementById(\'foo\')
  105.  
  106.         js.myFunction(\'my argument\') -> myFunction(\'my argument\')
  107.  
  108.         js.myFunction(True, 5, "it\'s a beautiful day") -> myFunction(true, 5, \'it\\\'s a beautiful day\')
  109.  
  110.         js.document.all["something"] -> document.all[\'something\']
  111.  
  112.         js[1, 2] -> [1, 2]
  113.  
  114.     XXX TODO support javascript object literals somehow? (They look like dicts)
  115.     perhaps like this:
  116.  
  117.         js["one": 1, "two": 2] -> {"one": 1, "two": 2}
  118.  
  119.     The livepage module includes many convenient instances of the js object.
  120.     It includes the literals:
  121.  
  122.         document
  123.         window
  124.         this
  125.         self
  126.  
  127.     It includes shorthand for commonly called javascript functions:
  128.  
  129.         alert -> alert
  130.         get -> document.getElementById
  131.         set -> nevow_setNode
  132.         append -> nevow_appendNode
  133.         prepend -> nevow.prependNode
  134.         insert -> nevow.insertNode
  135.  
  136.     It includes convenience calls against the client-side server object:
  137.  
  138.         server.handle(\'callMe\') -> server.handle(\'callMe\')
  139.  
  140.     It includes commonly-used fragments of javascript:
  141.  
  142.         stop -> ; return false;
  143.         eol -> \\n
  144.  
  145.     Stop is used to prevent the browser from executing it\'s default
  146.     event handler. For example:
  147.  
  148.         button(onclick=[server.handle(\'click\'), stop]) -> <button onclick="server.handle(\'click\'); return false;" />
  149.  
  150.     EOL is currently required to separate statements (this requirement
  151.     may go away in the future). For example:
  152.  
  153.         client.send([
  154.             alert(\'hello\'), eol,
  155.             alert(\'goodbye\')])
  156.  
  157.     XXX TODO: investigate whether rendering a 
  158.  between list elements
  159.     in a JavascriptContext has any ill effects.
  160.     '''
  161.     
  162.     def __init__(self, name = None):
  163.         if name is None:
  164.             name = []
  165.         
  166.         if isinstance(name, str):
  167.             name = [
  168.                 stan.raw(name)]
  169.         
  170.         self._children = name
  171.  
  172.     
  173.     def __getattr__(self, name):
  174.         if name == 'clone':
  175.             raise RuntimeError("Can't clone")
  176.         name == 'clone'
  177.         if self._children:
  178.             newchildren = self._children[:]
  179.             newchildren.append(stan.raw('.' + name))
  180.             return self.__class__(newchildren)
  181.         return self.__class__(name)
  182.  
  183.     
  184.     def __call__(self, *args):
  185.         if not self._children:
  186.             return self.__class__(args[0])
  187.         newchildren = self._children[:]
  188.         stuff = []
  189.         for x in args:
  190.             if isinstance(x, (basestring, stan.Tag, types.FunctionType, types.MethodType, types.UnboundMethodType)):
  191.                 x = (stan.raw("'"), SingleQuote(x), stan.raw("'"))
  192.             
  193.             stuff.append((x, stan.raw(',')))
  194.         
  195.         if stuff:
  196.             stuff[-1] = stuff[-1][0]
  197.         
  198.         newchildren.extend([
  199.             stan.raw('('),
  200.             stuff,
  201.             stan.raw(')')])
  202.         return self.__class__(newchildren)
  203.  
  204.     
  205.     def __getitem__(self, args):
  206.         if not isinstance(args, (tuple, list)):
  207.             args = (args,)
  208.         
  209.         newchildren = self._children[:]
  210.         stuff = [ (x, stan.raw(',')) for x in args ]
  211.         newchildren.extend([
  212.             stan.raw('['),
  213.             stuff,
  214.             stan.raw(']')])
  215.         return self.__class__(newchildren)
  216.  
  217.     
  218.     def __iter__(self):
  219.         '''Prevent an infinite loop if someone tries to do
  220.         for x in jsinstance:
  221.         '''
  222.         raise NotImplementedError, 'js instances are not iterable. (%r)' % (self,)
  223.  
  224.     
  225.     def __repr__(self):
  226.         return '%s(%r)' % (type(self).__name__, self._children)
  227.  
  228.  
  229.  
  230. def flattenJS(theJS, ctx):
  231.     new = JavascriptContext(ctx, tags.invisible[theJS])
  232.     return flat.serialize(theJS._children, new)
  233.  
  234. flat.registerFlattener(flattenJS, _js)
  235. js = _js()
  236. document = _js('document')
  237. get = document.getElementById
  238. window = _js('window')
  239. this = _js('this')
  240. self = _js('self')
  241. server = _js('server')
  242. alert = _js('alert')
  243. stop = _js('; return false;')
  244. eol = tags.raw('\n')
  245. set = js.nevow_setNode
  246. append = js.nevow_appendNode
  247. prepend = js.nevow_prependNode
  248. insert = js.nevow_insertNode
  249.  
  250. def assign(where, what):
  251.     '''Assign what to where. Equivalent to
  252.     where = what;
  253.     '''
  254.     return _js([
  255.         where,
  256.         stan.raw(' = '),
  257.         what])
  258.  
  259. setq = assign
  260.  
  261. def var(where, what):
  262.     """Define local variable 'where' and assign 'what' to it.
  263.     Equivalent to var where = what;
  264.     """
  265.     return _js([
  266.         stan.raw('var '),
  267.         where,
  268.         stan.raw(' = '),
  269.         what,
  270.         stan.raw(';')])
  271.  
  272.  
  273. def anonymous(block):
  274.     '''Turn block (any stan) into an anonymous JavaScript function
  275.     which takes no arguments. Equivalent to
  276.  
  277.     function () {
  278.         block
  279.     }
  280.     '''
  281.     return _js([
  282.         stan.raw('function() {\n'),
  283.         block,
  284.         stan.raw('\n}')])
  285.  
  286.  
  287. class IClientHandle(Interface):
  288.     
  289.     def hookupOutput(output, finisher = None):
  290.         '''hook up an output conduit to this live evil instance.
  291.         '''
  292.         pass
  293.  
  294.     
  295.     def send(script):
  296.         '''send a script through the output conduit to the browser.
  297.         If no output conduit is yet hooked up, buffer the script
  298.         until one is.
  299.         '''
  300.         pass
  301.  
  302.     
  303.     def handleInput(identifier, *args):
  304.         '''route some input from the browser to the appropriate
  305.         destination.
  306.         '''
  307.         pass
  308.  
  309.  
  310.  
  311. class IHandlerFactory(Interface):
  312.     
  313.     def locateHandler(ctx, name):
  314.         '''Locate a handler callable with the given name.
  315.         '''
  316.         pass
  317.  
  318.  
  319.  
  320. class _transient(object):
  321.     
  322.     def __init__(self, transientId, arguments = None):
  323.         self.transientId = transientId
  324.         if arguments is None:
  325.             arguments = []
  326.         elif isinstance(arguments, tuple):
  327.             arguments = list(arguments)
  328.         else:
  329.             raise TypeError, 'Arguments must be None or tuple'
  330.         self.arguments = arguments is None
  331.  
  332.     
  333.     def __call__(self, *arguments):
  334.         return type(self)(self.transientId, arguments)
  335.  
  336.  
  337.  
  338. def flattenTransient(transient, ctx):
  339.     thing = js.server.handle('--transient.%s' % (transient.transientId,), *transient.arguments)
  340.     return flat.serialize(thing, ctx)
  341.  
  342. flat.registerFlattener(flattenTransient, _transient)
  343.  
  344. class ClientHandle(object):
  345.     '''An object which represents the client-side webbrowser.
  346.     '''
  347.     implements(IClientHandle)
  348.     outputConduit = None
  349.     
  350.     def __init__(self, livePage, handleId, refreshInterval, targetTimeoutCount):
  351.         self.refreshInterval = refreshInterval
  352.         self.targetTimeoutCount = targetTimeoutCount
  353.         self.timeoutCount = 0
  354.         self.livePage = livePage
  355.         self.handleId = handleId
  356.         self.outputBuffer = []
  357.         self.bufferDeferreds = []
  358.         self.closed = False
  359.         self.closeNotifications = []
  360.         self.firstTime = True
  361.         self.timeoutLoop = LoopingCall(self.checkTimeout)
  362.         if refreshInterval:
  363.             self.timeoutLoop.start(self.refreshInterval)
  364.         
  365.         self._transients = { }
  366.         self.transientCounter = itertools.count().next
  367.         self.nextId = itertools.count().next
  368.  
  369.     
  370.     def transient(self, what, *args):
  371.         """Register a transient event handler, 'what'.
  372.         The callable 'what' can only be invoked by the
  373.         client once before being garbage collected.
  374.         Additional attempts to invoke the handler
  375.         will fail.
  376.         """
  377.         transientId = str(self.transientCounter())
  378.         self._transients[transientId] = what
  379.         return _transient(transientId, args)
  380.  
  381.     
  382.     def popTransient(self, transientId):
  383.         """Remove a transient previously registered
  384.         by a call to transient. Normally, this will be done
  385.         automatically when the transient is invoked.
  386.         However, you can invoke it yourself if you wish
  387.         to revoke the client's capability to call the
  388.         transient handler.
  389.         """
  390.         if DEBUG:
  391.             print 'TRANSIENTS', self._transients
  392.         
  393.         return self._transients.pop(transientId)
  394.  
  395.     
  396.     def _actuallySend(self, scripts):
  397.         output = self.outputConduit
  398.         written = []
  399.         
  400.         def writer(write):
  401.             written.append(write)
  402.  
  403.         
  404.         def finisher(finish):
  405.             towrite = '\n'.join(written)
  406.             jslog('<<<<<<\n%s\n' % towrite)
  407.             output.callback(towrite)
  408.  
  409.         flat.flattenFactory(scripts, self.outputContext, writer, finisher)
  410.         self.outputConduit = None
  411.         self.outputContext = None
  412.  
  413.     
  414.     def send(self, *script):
  415.         '''Send the stan "script", which can be flattened to javascript,
  416.         to the browser which is connected to this handle, and evaluate
  417.         it in the context of the browser window.
  418.         '''
  419.         if self.outputConduit:
  420.             self._actuallySend(script)
  421.         else:
  422.             self.outputBuffer.append(script)
  423.             self.outputBuffer.append(eol)
  424.  
  425.     
  426.     def setOutput(self, ctx, output):
  427.         self.timeoutCount = 0
  428.         self.outputContext = ctx
  429.         self.outputConduit = output
  430.         if self.outputBuffer:
  431.             if DEBUG:
  432.                 print 'SENDING BUFFERED', self.outputBuffer
  433.             
  434.             self._actuallySend(self.outputBuffer)
  435.             self.outputBuffer = []
  436.         
  437.  
  438.     
  439.     def _actuallyPassed(self, result, deferreds):
  440.         for d in deferreds:
  441.             d.callback(result)
  442.         
  443.  
  444.     
  445.     def _actuallyFailed(self, failure, deferreds):
  446.         for d in deferreds:
  447.             d.errback(failure)
  448.         
  449.  
  450.     
  451.     def checkTimeout(self):
  452.         if self.outputConduit is not None:
  453.             self.send(_js('null;'))
  454.             return None
  455.         self.timeoutCount += 1
  456.  
  457.     
  458.     def outputGone(self, failure, output):
  459.         self.outputConduit = None
  460.         if failure.check(error.ConnectionDone):
  461.             self._closeComplete()
  462.         else:
  463.             self._closeComplete(failure)
  464.  
  465.     
  466.     def _closeComplete(self, failure = None):
  467.         if self.closed:
  468.             return None
  469.         self.closed = True
  470.         self.timeoutLoop.stop()
  471.         self.timeoutLoop = None
  472.         for notify in self.closeNotifications[:]:
  473.             if failure is not None:
  474.                 notify.errback(failure)
  475.                 continue
  476.             self.closed
  477.             notify.callback(None)
  478.         
  479.         self.closeNotifications = []
  480.  
  481.     
  482.     def notifyOnClose(self):
  483.         """This will return a Deferred that will be fired when the
  484.         connection is closed 'normally', i.e. in response to handle.close()
  485.         . If the connection is lost in any other way (because the browser
  486.         navigated to another page, the browser was shut down, the network
  487.         connection was lost, or the timeout was reached), this will errback
  488.         instead."""
  489.         d = defer.Deferred()
  490.         self.closeNotifications.append(d)
  491.         return d
  492.  
  493.     
  494.     def close(self, executeScriptBeforeClose = ''):
  495.         if DEBUG:
  496.             print 'CLOSE WAS CALLED'
  497.         
  498.         d = self.notifyOnClose()
  499.         self.send(js.nevow_closeLive(executeScriptBeforeClose))
  500.         return d
  501.  
  502.     
  503.     def set(self, where, what):
  504.         self.send(js.nevow_setNode(where, what))
  505.  
  506.     
  507.     def prepend(self, where, what):
  508.         self.send(js.nevow_prependNode(where, what))
  509.  
  510.     
  511.     def append(self, where, what):
  512.         self.send(js.nevow_appendNode(where, what))
  513.  
  514.     
  515.     def alert(self, what):
  516.         self.send(js.alert(what))
  517.  
  518.     
  519.     def call(self, what, *args):
  520.         self.send(js(what)(*args))
  521.  
  522.     
  523.     def sendScript(self, string):
  524.         warnings.warn('[0.5] nevow.livepage.ClientHandle.sendScript is deprecated, use send instead.', DeprecationWarning, 2)
  525.         self.send(string)
  526.  
  527.  
  528.  
  529. class DefaultClientHandleFactory(object):
  530.     clientHandleClass = ClientHandle
  531.     
  532.     def __init__(self):
  533.         self.clientHandles = { }
  534.         self.handleCounter = itertools.count().next
  535.  
  536.     
  537.     def newClientHandle(self, livePage, refreshInterval, targetTimeoutCount):
  538.         handleid = str(self.handleCounter())
  539.         handle = self.clientHandleClass(livePage, handleid, refreshInterval, targetTimeoutCount)
  540.         self.clientHandles[handleid] = handle
  541.         (None, handle.notifyOnClose().addBoth)((lambda ign: self.deleteHandle(handleid)))
  542.         return handle
  543.  
  544.     
  545.     def deleteHandle(self, handleid):
  546.         del self.clientHandles[handleid]
  547.  
  548.     
  549.     def getHandleForId(self, handleId):
  550.         '''Override this to restore old handles on demand.
  551.         '''
  552.         return self.clientHandles[handleId]
  553.  
  554.  
  555. theDefaultClientHandleFactory = DefaultClientHandleFactory()
  556.  
  557. class OutputHandlerResource:
  558.     implements(inevow.IResource)
  559.     
  560.     def __init__(self, clientHandle):
  561.         self.clientHandle = clientHandle
  562.  
  563.     
  564.     def locateChild(self, ctx, segments):
  565.         raise NotImplementedError()
  566.  
  567.     
  568.     def renderHTTP(self, ctx):
  569.         request = inevow.IRequest(ctx)
  570.         neverEverCache(request)
  571.         activeChannel(request)
  572.         ctx.remember(jsExceptionHandler, inevow.ICanHandleException)
  573.         request.channel._savedTimeOut = None
  574.         d = defer.Deferred()
  575.         request.notifyFinish().addErrback(self.clientHandle.outputGone, d)
  576.         jsContext = JavascriptContext(ctx, tags.invisible())
  577.         self.clientHandle.livePage.rememberStuff(jsContext)
  578.         jsContext.remember(self.clientHandle, IClientHandle)
  579.         if self.clientHandle.firstTime:
  580.             self.clientHandle.livePage.goingLive(jsContext, self.clientHandle)
  581.             self.clientHandle.firstTime = False
  582.         
  583.         self.clientHandle.setOutput(jsContext, d)
  584.         return d
  585.  
  586.  
  587.  
  588. class InputHandlerResource:
  589.     implements(inevow.IResource)
  590.     
  591.     def __init__(self, clientHandle):
  592.         self.clientHandle = clientHandle
  593.  
  594.     
  595.     def locateChild(self, ctx, segments):
  596.         raise NotImplementedError()
  597.  
  598.     
  599.     def renderHTTP(self, ctx):
  600.         self.clientHandle.timeoutCount = 0
  601.         request = inevow.IRequest(ctx)
  602.         neverEverCache(request)
  603.         activeChannel(request)
  604.         ctx.remember(self.clientHandle, IClientHandle)
  605.         ctx.remember(jsExceptionHandler, inevow.ICanHandleException)
  606.         self.clientHandle.livePage.rememberStuff(ctx)
  607.         handlerName = request.args['handler-name'][0]
  608.         arguments = request.args.get('arguments', ())
  609.         jslog('>>>>>>\n%s %s\n' % (handlerName, arguments))
  610.         if handlerName.startswith('--transient.'):
  611.             handler = self.clientHandle.popTransient(handlerName.split('.')[-1])
  612.         else:
  613.             handler = self.clientHandle.livePage.locateHandler(ctx, request.args['handler-path'], handlerName)
  614.         jsContext = JavascriptContext(ctx, tags.invisible[handler])
  615.         towrite = []
  616.         
  617.         def writer(r):
  618.             jslog('WRITE ', r)
  619.             towrite.append(r)
  620.  
  621.         
  622.         def finisher(r):
  623.             jslog('FINISHED', r)
  624.             writestr = ''.join(towrite)
  625.             jslog('<><><>\n%s\n' % (writestr,))
  626.             request.write(writestr)
  627.             request.finish()
  628.             return r
  629.  
  630.         result = handler(jsContext, *arguments)
  631.         jslog('RESULT ', result)
  632.         if result is None:
  633.             return defer.succeed('')
  634.         return self.clientHandle.livePage.flattenFactory(result, jsContext, writer, finisher)
  635.  
  636.  
  637.  
  638. class DefaultClientHandlesResource(object):
  639.     implements(inevow.IResource)
  640.     clientResources = {
  641.         'input': InputHandlerResource,
  642.         'output': OutputHandlerResource }
  643.     clientFactory = theDefaultClientHandleFactory
  644.     
  645.     def locateChild(self, ctx, segments):
  646.         handleId = segments[0]
  647.         handlerType = segments[1]
  648.         client = self.clientFactory.clientHandles[handleId]
  649.         return (self.clientResources[handlerType](client), segments[2:])
  650.  
  651.  
  652. theDefaultClientHandlesResource = DefaultClientHandlesResource()
  653.  
  654. class attempt(defer.Deferred):
  655.     '''Attempt to do \'stuff\' in the browser. callback on the server
  656.     if \'stuff\' executes without raising an exception. errback on the
  657.     server if \'stuff\' raises a JavaScript exception in the client.
  658.  
  659.     Used like this:
  660.  
  661.     def printIt(what):
  662.         print "Woo!", what
  663.  
  664.     C = IClientHandle(ctx)
  665.     C.send(
  666.         attempt(js("1+1")).addCallback(printIt))
  667.  
  668.     C.send(
  669.         attempt(js("thisWillFail")).addErrback(printIt))
  670.     '''
  671.     
  672.     def __init__(self, stuff):
  673.         self.stuff = stuff
  674.         defer.Deferred.__init__(self)
  675.  
  676.  
  677.  
  678. def flattenAttemptDeferred(d, ctx):
  679.     
  680.     def attemptComplete(ctx, result, reason = (None,)):
  681.         if result == 'success':
  682.             d.callback(None)
  683.         else:
  684.             d.errback(ClientSideException(reason))
  685.  
  686.     transient = IClientHandle(ctx).transient(attemptComplete)
  687.     return flat.serialize([
  688.         _js('try {\n    '),
  689.         d.stuff,
  690.         _js('\n    '),
  691.         transient('success'),
  692.         _js('\n} catch (e) {\n    '),
  693.         transient('failure', js.e),
  694.         _js('}')], ctx)
  695.  
  696. flat.registerFlattener(flattenAttemptDeferred, attempt)
  697.  
  698. class IOutputEvent(Interface):
  699.     pass
  700.  
  701.  
  702. class IInputEvent(Interface):
  703.     pass
  704.  
  705.  
  706. class ExceptionHandler(object):
  707.     
  708.     def renderHTTP_exception(self, ctx, failure):
  709.         log.msg('Exception during input event:')
  710.         log.err(failure)
  711.         request = inevow.IRequest(ctx)
  712.         request.write("throw new Error('Server side error: %s')" % (failure.getErrorMessage().replace("'", "\\'").replace('\n', '\\\n'),))
  713.         request.finish()
  714.  
  715.     
  716.     def renderInlineException(self, ctx, reason):
  717.         """TODO: I don't even think renderInlineException is ever called by anybody
  718.         """
  719.         pass
  720.  
  721.  
  722. jsExceptionHandler = ExceptionHandler()
  723.  
  724. def neverEverCache(request):
  725.     ''' Set headers to indicate that the response to this request should never,
  726.     ever be cached.
  727.     '''
  728.     request.setHeader('Cache-Control', 'no-store, no-cache, must-revalidate')
  729.     request.setHeader('Pragma', 'no-cache')
  730.  
  731.  
  732. def activeChannel(request):
  733.     """Mark this connection as a 'live' channel by setting the Connection: close
  734.     header and flushing all headers immediately.
  735.     """
  736.     request.setHeader('Connection', 'close')
  737.     request.write('')
  738.  
  739.  
  740. class LivePage(rend.Page):
  741.     '''A Page which is Live provides asynchronous, bidirectional RPC between
  742.     Python on the server and JavaScript in the client browser. A LivePage must
  743.     include the "liveglue" JavaScript which includes a unique identifier which
  744.     is assigned to every page render of a LivePage and the JavaScript required
  745.     for the client to communicate asynchronously with the server.
  746.  
  747.     A LivePage grants the client browser the capability of calling server-side
  748.     Python methods using a small amount of JavaScript code. There are two
  749.     types of Python handler methods, persistent handlers and transient handlers.
  750.  
  751.     1) To grant the client the capability to call a persistent handler over and over
  752.         as many times as it wishes, subclass LivePage and provide handle_foo
  753.         methods. The client can then call handle_foo by executing the following
  754.         JavaScript:
  755.  
  756.           server.handle(\'foo\')
  757.  
  758.         handle_foo will be invoked because the default implementation of
  759.         locateHandler looks for a method prefixed handle_*. To change this,
  760.         override locateHandler to do what you wish.
  761.  
  762.     2) To grant the client the capability of calling a handler once and
  763.         exactly once, use ClientHandle.transient to register a callable and
  764.         embed the return result in a page to render JavaScript which will
  765.         invoke the transient handler when executed. For example:
  766.  
  767.         def render_clickable(self, ctx, data):
  768.             def hello(ctx):
  769.                 return livepage.alert("Hello, world. You can only click me once.")
  770.  
  771.             return ctx.tag(onclick=IClientHandle(ctx).transient(hello))
  772.  
  773.         The return result of transient can also be called to pass additional
  774.         arguments to the transient handler. For example:
  775.  
  776.         def render_choice(self, ctx, data):
  777.             def chosen(ctx, choseWhat):
  778.                 return livepage.set(
  779.                     "choosable",
  780.                     ["Thanks for choosing ", choseWhat])
  781.  
  782.             chooser = IClientHandle(ctx).transient(chosen)
  783.  
  784.             return span(id="choosable")[
  785.                 "Choose one:",
  786.                 p(onclick=chooser("one"))["One"],
  787.                 p(onclick=chooser("two"))["Two"]]
  788.  
  789.         Note that the above situation displays temporary UI to the
  790.         user. When the user invokes the chosen handler, the UI which
  791.         allowed the user to invoke the chosen handler is removed from
  792.         the client. Thus, it is important that the transient registration
  793.         is deleted once it is invoked, otherwise uncollectable garbage
  794.         would accumulate in the handler dictionary. It is also important
  795.         that either the one or the two button consume the same handler,
  796.         since it is an either/or choice. If two handlers were registered,
  797.         the untaken choice would be uncollectable garbage.
  798.     '''
  799.     refreshInterval = 30
  800.     targetTimeoutCount = 3
  801.     clientFactory = theDefaultClientHandleFactory
  802.     
  803.     def renderHTTP(self, ctx):
  804.         if not self.cacheable:
  805.             neverEverCache(inevow.IRequest(ctx))
  806.         
  807.         return rend.Page.renderHTTP(self, ctx)
  808.  
  809.     
  810.     def locateHandler(self, ctx, path, name):
  811.         return getattr(self, 'handle_%s' % (name,))
  812.  
  813.     
  814.     def goingLive(self, ctx, handle):
  815.         """This particular LivePage instance is 'going live' from the
  816.         perspective of the ClientHandle 'handle'. Override this to
  817.         get notified when a new browser window observes this page.
  818.  
  819.         This means that a new user is now looking at the page, an old
  820.         user has refreshed the page, or an old user has opened a new
  821.         window or tab onto the page.
  822.  
  823.         This is the first time the ClientHandle instance is available
  824.         for general use by the server. This Page may wish to keep
  825.         track of the ClientHandle instances depending on how your
  826.         application is set up.
  827.         """
  828.         pass
  829.  
  830.     
  831.     def child_livepage_client(self, ctx):
  832.         return theDefaultClientHandlesResource
  833.  
  834.     
  835.     def render_liveid(self, ctx, data):
  836.         warnings.warn("You don't need a liveid renderer any more; just liveglue is fine.", DeprecationWarning)
  837.         return ''
  838.  
  839.     cacheable = False
  840.     
  841.     def render_liveglue(self, ctx, data):
  842.         if not self.cacheable:
  843.             handleId = ("'", self.clientFactory.newClientHandle(self, self.refreshInterval, self.targetTimeoutCount).handleId, "'")
  844.         else:
  845.             handleId = 'null'
  846.         return [
  847.             tags.script(type = 'text/javascript')[('var nevow_clientHandleId = ', handleId, ';')],
  848.             tags.script(type = 'text/javascript', src = url.here.child('nevow_glue.js'))]
  849.  
  850.  
  851. setattr(LivePage, 'child_nevow_glue.js', static.File(util.resource_filename('nevow', 'liveglue.js'), 'text/javascript'))
  852. glue = tags.directive('liveglue')
  853. ctsTemplate = "nevow_clientToServerEvent('%s',this,''%s)%s"
  854. handledEventPostlude = '; return false;'
  855.  
  856. class handler(object):
  857.     callme = None
  858.     args = ()
  859.     identifier = None
  860.     
  861.     def __init__(self, *args, **kw):
  862.         '''**DEPRECATED** [0.5]
  863.  
  864.         Handler is now deprecated. To expose server-side code to the client
  865.         to be called by JavaScript, read the LivePage docstring.
  866.         '''
  867.         warnings.warn("[0.5] livepage.handler is deprecated; Provide handle_foo methods (or override locateHandler) on your LivePage and use (in javascript) server.handle('foo'), or use ClientHandle.transient to register a one-shot handler capability.", DeprecationWarning, 2)
  868.         if not callable(args[0]) or isinstance(args[0], _js):
  869.             self.args = args
  870.             return None
  871.         self.callme = args[0]
  872.         self(*args[1:], **kw)
  873.  
  874.     
  875.     def __call__(self, *args, **kw):
  876.         if self.callme is None:
  877.             self.callme = args[0]
  878.             args = args[1:]
  879.         
  880.         self.args += args
  881.         self.outsideAttribute = kw.get('outsideAttribute')
  882.         bubble = kw.get('bubble')
  883.         if bubble:
  884.             self.postlude = ';'
  885.         else:
  886.             self.postlude = handledEventPostlude
  887.         if 'identifier' in kw:
  888.             self.identifier = kw['identifier']
  889.         
  890.         return self
  891.  
  892.     content = property((lambda self: flt(self)))
  893.  
  894.  
  895. def flattenHandler(handler, ctx):
  896.     client = IClientHandle(ctx)
  897.     iden = handler.identifier
  898.     if iden is None:
  899.         iden = client.nextId()
  900.     
  901.     iden = '--handler-%s' % (iden,)
  902.     setattr(IHandlerFactory(ctx), 'handle_%s' % (iden,), handler.callme)
  903.     isAttrib = not (handler.outsideAttribute)
  904.     new = JavascriptContext(ctx, tags.invisible[handler.args], isAttrib = isAttrib)
  905.     rv = flat.flatten(js.nevow_clientToServerEvent(*(iden, this, '') + handler.args), new)
  906.     rv += handler.postlude
  907.     return tags.xml(rv)
  908.  
  909. flat.registerFlattener(flattenHandler, handler)
  910.  
  911. def flt(stan, quote = True, client = None, handlerFactory = None):
  912.     '''Flatten some stan to a string suitable for embedding in a javascript
  913.     string.
  914.  
  915.     If quote is True, apostrophe, quote, and newline will be quoted
  916.     '''
  917.     warnings.warn("[0.5] livepage.flt is deprecated. Don't use it.", DeprecationWarning, 2)
  918.     testutil = testutil
  919.     import nevow
  920.     fr = testutil.FakeRequest()
  921.     ctx = context.RequestContext(tag = fr)
  922.     ctx.remember(client, IClientHandle)
  923.     ctx.remember(handlerFactory, IHandlerFactory)
  924.     ctx.remember(None, inevow.IData)
  925.     fl = flat.flatten(stan, ctx = ctx)
  926.     if quote:
  927.         fl = fl.replace('\\', '\\\\').replace("'", "\\'").replace('\n', '\\n')
  928.     
  929.     return fl
  930.  
  931.